﻿using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Gma.UserActivityMonitor;
using mmoss.orm;

namespace greenwerkz.PlantMonitor
{
    public partial class FrmMain : Form
    {
        //user settings
        public frmContainer.loginUser CurrentUser
        {
            get
            {
                return (((frmContainer)this.MdiParent).LoggedInUser);
            }
        }
        public int CurrentGrowOperation
        {
            get
            {
                return (((frmContainer)this.MdiParent).LoggedInUser.growFacilityID);
            }
        }
        public string CurrentScanTag { get; set; }
        public int UserID
        {
            get
            {
                return (((frmContainer)this.MdiParent).LoggedInUser.umbracoMemberUserID);
            }
        }

        //web services
        private greenwerkz.PlantMonitor.plants.Plants _wsPlant = new greenwerkz.PlantMonitor.plants.Plants();
        private greenwerkz.PlantMonitor.patients.patients _wsPatient = new greenwerkz.PlantMonitor.patients.patients();
        private greenwerkz.PlantMonitor.strains.Strains _wsStrains = new greenwerkz.PlantMonitor.strains.Strains();
        private greenwerkz.PlantMonitor.plants.Plant[] ReservationList { get; set; }

        public greenwerkz.PlantMonitor.plants.Plants WsPlant
        {
            get { return _wsPlant; }
        }
        public greenwerkz.PlantMonitor.patients.patients WsPatient
        {
            get { return _wsPatient; }
        }
        public greenwerkz.PlantMonitor.strains.Strains WsStrain
        {
            get { return _wsStrains; }
        }

        
        //webcam
        WebCamera.WebCam l_cam;
        public int plantPictureCount = 0;

        //enumerations
        public enum Operation
        {
            changeState = 1,
            changeLocation = 2,
            Info = 3,
            Complete=4,
            Kill = 5,
            Weigh = 6,
            Idle = 99
        }
        public enum PlantState
        {
            Veg=1,
            Flowering=2,
            Trim=3,
            Drying= 4,
            Curing= 5,
            WeighComplete= 6,
            DeadOrRemoved=99
        }

        //current info
        greenwerkz.PlantMonitor.plants.Plant _currentPlant = new greenwerkz.PlantMonitor.plants.Plant();
        private Operation _currentOperation;
        private int _currentLocation;
        private int _currentAction;
        private int _currentPlantID;
        private PlantState _currentState;

        //scanning
        private bool scanProcessing { get; set; }
        private string scanString { get; set; }

        //current variables
        public greenwerkz.PlantMonitor.plants.Plant CurrentPlant
        {
            get { return _currentPlant; }
            set { _currentPlant = value; }
        }
        public Operation CurrentOperation
        {
            get { return _currentOperation; }
            set { _currentOperation = value; }
        }
        public PlantState CurrentState
        {
            get { return _currentState; }
            set { _currentState = value; }
        }
        public int CurrentPlantID
        {
            get { return _currentPlantID; }
            set { _currentPlantID = value; }
        }
        public int CurrentLocation
        {
            get { return _currentLocation; }
            set { _currentLocation = value; }
        }


        //main stuff
        public FrmMain()
        {
            InitializeComponent();
            disableNewScreen();
            //cboLocation.SelectedIndexChanged+=new EventHandler(cboLocation_SelectedIndexChanged);
            //cboState.SelectedIndexChanged += new EventHandler(cboState_SelectedIndexChanged);
            //USE global hook manager
            HookManager.KeyPress += new KeyPressEventHandler(HookManager_KeyPress);
            CurrentOperation = Operation.Idle;
        }

        void HookManager_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((int)e.KeyChar)==126)
            {
                //this is beginning or end of sequence with tilde (~)
                //note - scanner must be set such that prefix/suffix set to tilde
                if (scanProcessing)
                {
                    scanProcessing = false;
                    //push the string to handler
                    barScanned(scanString);
                    scanString = "";
                }
                else
                {
                    scanProcessing = true;
                    scanString = "";
                }
            }
            if (scanProcessing && ((int)e.KeyChar)!=126)
            {
                scanString = scanString + e.KeyChar;
            }
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            
        }
        private void Form1_Load(object sender, EventArgs e)
        {

            
            //welcome message
            lblLoginMsg.Text = "Welcome " + CurrentUser.userFName + " " + CurrentUser.userLName;
            
            //initial defaults
            initializeCBOs();
            cboMoveLocation.SelectedIndexChanged += new EventHandler(cboMoveLocation_SelectedIndexChanged);

            //webcam init
            l_cam = new WebCamera.WebCam();
            l_cam.Container = pictureBox1;

            //set ws timeouts
            _wsPatient.Timeout = -1;
            _wsPlant.Timeout = -1;

            //wire events
            dgReservationList.CellClick += new DataGridViewCellEventHandler(dgReservationList_CellClick);
            tbMonitor.SelectedIndexChanged += new EventHandler(tbMonitor_SelectedIndexChanged);

            //set default mode
            btnInfo_Click(sender,e);
        }

        void tbMonitor_SelectedIndexChanged(object sender, EventArgs e)
        {
            //tab was clicked.
            switch (((TabControl)sender).SelectedTab.Name)
            {
                case "tabKill":
                    if (CurrentOperation!=Operation.Kill) 
                    {
                        MessageBox.Show("Must be in Kill mode");
                        tbMonitor.SelectedTab = tabInfo;
                    }
                    break;
                case "tabEdit":
                    break;
                case "tabImage":
                    if (CurrentPlant.PlantID == 0)
                    {
                        MessageBox.Show("Select plant before entering picture");
                        tbMonitor.SelectedTab = tabInfo;
                    }
                    break;
                case "tabInfo":
                    break;
                case "tabWeigh":
                    if (CurrentOperation != Operation.Kill && CurrentOperation != Operation.changeState)
                    {
                        MessageBox.Show("Must be in proper operation to weigh");
                        tbMonitor.SelectedTab = tabInfo;
                    }
                    break;
            }
        }

        #region addedit tab methods

        private void buildEditScreen()
        {
            //build the edit screen for the add/edit
            btnAdd.Visible = false;
            btnAddPlant.Visible = false;
            btnComplete.Visible = false;
            btnAddCancel.Visible = false;

            btnAddEditUpdate.Visible = true;
            btnAddEditCancelReservation.Visible = true;
        }

        private void buildAddScreen()
        {
            //build the edit screen for the add/edit
            btnAdd.Visible = false;
            btnAddPlant.Visible = true;
            btnComplete.Visible = true;
            btnAddCancel.Visible = true;

            btnAddEditUpdate.Visible = false;
            btnAddEditCancelReservation.Visible = false;
        }

        private void disableNewScreen()
        {
            //txtPlantID.Enabled=false;
            cboCondition.Enabled = false;
            cboLocation.Enabled = false;
            cboPatient.Enabled = false;
            cboState.Enabled = false;
            cboStrain.Enabled = false;
            btnAdd.Enabled = false;
            btnAddPlant.Enabled = true;
            btnComplete.Enabled = false;
            btnAutoPickPatient.Enabled = false;
            btnAddCancel.Enabled = false;

        }
        private void enableNewScreen()
        {
            //txtPlantID.Enabled=true;
            cboCondition.Enabled = true;
            cboLocation.Enabled = true;
            cboPatient.Enabled = true;
            cboState.Enabled = false;
            cboStrain.Enabled = true;
            btnAdd.Enabled = true;
            btnAddPlant.Enabled = false;
            btnComplete.Enabled = true;
            btnAutoPickPatient.Enabled = true;
            btnAddCancel.Enabled = true;
        }
        void dgReservationList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //click in the reservation cell
            if (MessageBox.Show("Would you like to assign this?", "Assign Reservation", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                editPlant(ReservationList[e.RowIndex]);
            }
        }
        private void editPlant(greenwerkz.PlantMonitor.plants.Plant l_plantInfo)
        {

            cboStrain.SelectedValue = l_plantInfo.PlantStrain.UmbracoNodeID;
            txtAddEditPatient.Text = l_plantInfo.PlantMemberID.ToString();
            txtAddEditTagID.Text = l_plantInfo.PlantTagID.ToString();
            txtPlantID.Text = l_plantInfo.PlantID.ToString();
            CurrentPlant = l_plantInfo;
            buildEditScreen();
            enableNewScreen();
        }

        #endregion
        
        private void buildReservationList()
        {
            ReservationList = WsPlant.selectReservedPlantsByGrowOperation(
                CurrentUser.growFacilityID
                );
            dgReservationList.AutoGenerateColumns = false;
            dgReservationList.DataSource = ReservationList;
        }
        void cboMoveLocation_SelectedIndexChanged(object sender, EventArgs e)
        {
            //index changed
            CurrentLocation = int.Parse(((greenwerkz.PlantMonitor.plants.KeyValuePair)cboMoveLocation.SelectedItem).Key.ToString());
            lblCurrentMode.Text = "Moving to " + castCombo(cboMoveLocation.SelectedItem).Value;
        }
        private void initializeCBOs()
        {
            //build the initial comboboxes
            //greenwerkz.PlantMonitor.ws.patients wsConsumer = new greenwerkz.PlantMonitor.ws.patients();
            //greenwerkz.PlantMonitor.plants.Plants wsStrains = new greenwerkz.PlantMonitor.plants.Plants();
            //patients
            /*
            List<KeyValuePair> pulldowns = new List<KeyValuePair>();
            foreach (greenwerkz.PlantMonitor.ws.GWpatient childPatient in WsPatient.SelectPatientAll().Where(s => s.PatientCaregiver != null))
            {
                pulldowns.Add(new KeyValuePair(childPatient.MemberID, childPatient.MemberUserName));
            }
            cboPatient.DataSource = pulldowns;
            */
            //strains
            /*            
            List<KeyValuePair> pulldownStrain = new List<KeyValuePair>();
            foreach (greenwerkz.PlantMonitor.strains.strain childStrain in _wsStrains.getAllStrains())
            {
                //pulldownStrain.Add(new KeyValuePair(childStrain.UmbracoNodeID, childStrain.ShortName));
                pulldownStrain.Add(new KeyValuePair(childStrain.UmbracoNodeID, childStrain.ShortName));
            }
            cboStrain.DataSource = pulldownStrain;
             * */

            cboStrain.DataSource = WsStrain.getAllStrains();
            cboStrain.DisplayMember = "LongName";
            cboStrain.ValueMember = "UmbracoNodeID";

            //get the next ID
            txtPlantID.Text = WsPlant.getNextPlantID().ToString();

            //bind the location
            greenwerkz.PlantMonitor.plants.KeyValuePair[] KVlocations = WsPlant.getPlantLocation();
            greenwerkz.PlantMonitor.plants.KeyValuePair[] KVlocations2 = WsPlant.getPlantLocation();
            cboLocation.DataSource = KVlocations;
            cboLocation.ValueMember = "Key";
            cboLocation.DisplayMember = "Value";

            cboMoveLocation.DataSource = KVlocations2;
            cboMoveLocation.ValueMember = "Key";
            cboMoveLocation.DisplayMember = "Value";

            //bind the condition
            cboCondition.DataSource = WsPlant.getPlantCondition();
            cboCondition.ValueMember = "Key";
            cboCondition.DisplayMember = "Value";

            //bind the state
            cboState.DataSource = WsPlant.getPlantState();
            cboState.ValueMember = "Key";
            cboState.DisplayMember = "Value";

        }
        private void refreshGrids()
        {
            //refresh the status grids

        }
        private void btnAutoPickPatient_Click(object sender, EventArgs e)
        {
            //get a random ID based on what plants a patient has
        }

        #region mode methods

        private void btnSubmitWeight_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure the numbers are correct??", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                //submit the weigh in
                if (!WsPlant.insertPlantWeight(
                    CurrentPlant.PlantID
                    , CurrentUser.umbracoMemberUserID
                    , short.Parse(((int)CurrentState).ToString())
                    , double.Parse(txtWeighWeight.Text)
                    ))
                {
                    MessageBox.Show("Error in saving weight");
                }
                else
                {
                    MessageBox.Show("weight saved");
                }

            }

        }
        private void btnWater_Click(object sender, EventArgs e)
        {
            lblCurrentMode.Text = "Watering";
        }
        private void btnVegging_Click(object sender, EventArgs e)
        {

            lblCurrentMode.Text = "Move to xxxx - waiting on location";
            CurrentOperation = Operation.changeLocation;
            cboMoveLocation.Visible = true;
        }
        private void btnFlower_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.Flowering;
            lblCurrentMode.Text = "Move to Flower";
        }
        
        #endregion

        #region action methods

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //call the web service
            if (!savePlant()) MessageBox.Show("Error in adding plant.  Check values");

        }
        private KeyValuePair castCombo(object selectedValue)
        {
            greenwerkz.PlantMonitor.plants.KeyValuePair kvselectedValue = ((greenwerkz.PlantMonitor.plants.KeyValuePair)selectedValue);
            return new KeyValuePair(kvselectedValue.Key, kvselectedValue.Value);
        }

        private void btnAddPlant_Click(object sender, EventArgs e)
        {
            enableNewScreen();
            txtPlantID.Focus();
            //autoselect the patient record for this ID
            txtAddEditPatient.Text = WsPatient.selectPatientForPlant(true, CurrentUser.growFacilityID).MemberID.ToString();
            txtPlantID.Text = WsPlant.getNextPlantID().ToString();
            txtAddEditTagID.Text = "";
            cboCondition.SelectedIndex = 2;
        }

        private void btnComplete_Click(object sender, EventArgs e)
        {
            if (!savePlant()) MessageBox.Show("Error in adding plant");
            disableNewScreen();

        }

        private void btnCut_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.Trim;
            CurrentOperation = Operation.changeState;
            lblCurrentMode.Text = "Trimming";
        }

        private void btnDry_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.Drying;
            CurrentOperation = Operation.changeState;
            lblCurrentMode.Text = "Dry Weigh-in";
        }

        private void btnWeigh_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.WeighComplete;
            CurrentOperation = Operation.Complete;
            lblCurrentMode.Text = "Weigh In";
        }

        private void btnInfo_Click(object sender, EventArgs e)
        {
            CurrentOperation = Operation.Info;
            lblCurrentMode.Text = "Plant Info";
            cboMoveLocation.Visible = false;
        }
        
        #endregion

        #region database calls
        private void ws_insertPlant(int l_plantState, string l_plantID, Guid l_picGUID, byte[] l_picByteArracy, string l_imageType)
        {
            WsPlant.InsertPlantPicture(l_plantState, int.Parse(l_plantID), l_picGUID, l_picByteArracy, l_imageType);
        }
        private bool savePlant()
        {


            if (txtAddEditTagID.Text.Trim() == "")
            {
                MessageBox.Show("Must provide Tag ID");
                txtAddEditTagID.Focus();
                return false;
            }
            bool l_bCall = WsPlant.InsertPlant
                (
                CurrentUser.growFacilityID
                , txtAddEditTagID.Text
                , int.Parse(txtPlantID.Text)
                , int.Parse(cboState.SelectedValue.ToString())
                , int.Parse(cboStrain.SelectedValue.ToString())
                , int.Parse(txtAddEditPatient.Text)
                , castCombo(cboLocation.SelectedItem).Key
                );

            if (l_bCall)
            {
                //select plant
                //CurrentPlant = WsPlant.getPlantInfoByTag(txtAddEditPatient.Text);
                //CurrentPlantID = CurrentPlant.PlantID;
                //CurrentScanTag = 
                MessageBox.Show("Plant updated");
                tbMonitor.SelectedTab = tabInfo;
                //displayPlantInfo();
                CurrentOperation = Operation.Info;
                lblCurrentMode.Text = "Plant Info"; 
                barScanned(txtAddEditTagID.Text);
                buildReservationList();
            }
            return l_bCall;

        }
        #endregion

        private void btnAddCancel_Click(object sender, EventArgs e)
        {
            disableNewScreen();
        }
        private void displayPlantInfo()
        {
            if (CurrentPlant.PlantID == 0)
            {
                if (MessageBox.Show("No Plant with this ID"+Environment.NewLine+"Would you like to add?","New Plant",MessageBoxButtons.YesNo)==DialogResult.Yes)
                {
                    tbMonitor.SelectedTab = tabEdit;
                    enableNewScreen();
                    //txtPlantID.Text=CurrentPlantID.ToString();
                    txtAddEditTagID.Text = CurrentScanTag;
                    txtPlantID.Text = WsPlant.getNextPlantID().ToString();
                    txtAddEditPatient.Text = WsPatient.selectPatientForPlant(true, CurrentUser.growFacilityID).MemberID.ToString();
                    //txtAddEditTagID.Text = CurrentPlant.PlantTagID;
                    //set the 
                }
                return;
            }
            //bind info screen
            lblInfoDateHarvest.Text = CurrentPlant.PlantHavestDate.ToString();
            lblInfoDateStart.Text = CurrentPlant.PlantStartDate.ToString();
            //lblInfoPatient.Text = CurrentPlant.Member.MemberUserName;
            lblInfoPatient.Text = CurrentPlant.Member.MemberID.ToString();
            lblInfoPlantID.Text = CurrentPlant.PlantID.ToString();
            lblInfoStrain.Text = CurrentPlant.PlantStrain.LongName;

            //bind picture
            plantPictureCount=0;
            handlePictureButtons();

            //bind comment history
            if (CurrentPlant.PlantComments.Length > 0)
            {
                dgNotes.DataSource = CurrentPlant.PlantComments;
            }
            //bind state history
            if (CurrentPlant.PlantStates.Length > 0)
            {
                dgStateHistory.DataSource = CurrentPlant.PlantStates;
            }
            //bind location history
            if (CurrentPlant.PlantLocations.Length > 0)
            {
                dgLocationHist.DataSource = CurrentPlant.PlantLocations;
            }
        }
        private void barScanned(string l_sPlantID)
        {
            if (l_sPlantID.Trim() == "")
            {
                MessageBox.Show("Tag cannot be blank");
                return;
            }
            int iPlantID;
            /*
            if (!int.TryParse(l_sPlantID, out iPlantID))
            {
                MessageBox.Show("Error in scan.  Must be numeric");
                return;
            }
            */
            try
            {
                CurrentScanTag = l_sPlantID;
                CurrentPlant = WsPlant.getPlantInfoByTag(l_sPlantID);
                iPlantID = CurrentPlant.PlantID;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error getting plant with tag #" + l_sPlantID);
                return;
            }
            CurrentPlantID = iPlantID;

            //enable/disable buttons based on plant
            btnActionToFlower.Visible = false;
            cboCondition.SelectedIndex = 2;
            if (iPlantID == 0)
            {
                btnActionToFlower.Visible = false;
            }
            else
            {
                if (CurrentPlant.PlantStates[CurrentPlant.PlantStates.Length - 1].PlantStateID == 1)
                {
                    btnActionToFlower.Visible = true;
                }
            }

            lblCurrentPlant.Text = "Plant ID# " + iPlantID.ToString();
            //call web service for plant info
            //call web service with event
            switch (CurrentOperation)
            {
                case Operation.Idle:
                    MessageBox.Show("Must select operation");
                    break;
                case Operation.Info:
                    CurrentPlant = WsPlant.getPlantInfo(CurrentPlantID);
                    displayPlantInfo();
                    break;
                case Operation.changeLocation:
                    WsPlant.ChangePlantLocation
                        (CurrentPlantID
                        , CurrentLocation
                        );
                    break;
                case Operation.changeState:
                    WsPlant.ChangePlantState
                        (CurrentPlantID
                        , (int)CurrentState
                        );
                    if (CurrentState == PlantState.Drying)
                    {
                        //drying plant
                        tbMonitor.SelectedIndex = 3;
                        lblweighType.Text = "Wet Weight";
                        tabWeigh.Select();
                        break;
                    }
                    if (CurrentState == PlantState.Trim)
                    {
                        //drying plant
                        tbMonitor.SelectedIndex = 3;
                        lblweighType.Text = "Wet Weight";
                        tabWeigh.Select();
                        break;
                    }
                    if (CurrentState == PlantState.Curing)
                    {
                        //drying plant
                        tbMonitor.SelectedIndex = 3;
                        lblweighType.Text = "Pre-curing Weight";
                        tabWeigh.Select();
                        break;
                    }
                    if (CurrentState == PlantState.WeighComplete)
                    {
                        //drying plant
                        tbMonitor.SelectedIndex = 3;
                        lblweighType.Text = "Dry Weight";
                        tabWeigh.Select();
                        break;
                    }
                    break;
                case Operation.Complete:
                    tbMonitor.SelectedIndex = 3;
                    tabWeigh.Select();
                    lblweighType.Text = "Cured Weight";
                    break;
                case Operation.Kill:
                    //bring up kill tab
                    break;
            }
            /*
            if (tbActive.SelectedIndex == 0)
            {
                //reload the info
                CurrentPlant = WsPlant.getPlantInfo(CurrentPlantID);
                displayPlantInfo();
            }
             * */
        }
        private void btnMock_Click(object sender, EventArgs e)
        {
            barScanned(txtMockID.Text);
        }
        public void LoginUser(int l_memberNodeID, int l_growOperationID)
        {
            //CurrentGrowOperation = l_growOperationID;
            buildReservationList();
            this.Show();

            //set labels
            lblGrowOpp.Text = "location #" + CurrentGrowOperation.ToString();
            lblCurrentUser.Text = CurrentUser.userName;

        }

        #region picture methods

        private void btnTakePic_Click(object sender, EventArgs e)
        {

            fdMockFile.InitialDirectory = ".\\";
            fdMockFile.Filter = "jpg (*.jpg)|*.jpg|gif (*.gif)|*.gif";
            fdMockFile.FilterIndex = 0;
            fdMockFile.RestoreDirectory = false; //true;
            if (fdMockFile.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            Stream strm;
            StreamReader reader;
            try
            {
                FileInfo l_info = new FileInfo(fdMockFile.FileName);
                strm = fdMockFile.OpenFile();
                FileStream objfilestream = new FileStream(fdMockFile.FileName, FileMode.Open, FileAccess.Read);
                int len = (int)objfilestream.Length;
                Byte[] mybytearray = new Byte[len];
                objfilestream.Read(mybytearray, 0, len);

                //bcj - fix this manual update
                
                ws_insertPlant(3, CurrentPlant.PlantID.ToString(), Guid.NewGuid(), mybytearray, l_info.Extension);

                //reload camera settings
                reloadCameraSettings();

            }
            catch (Exception ex)
            {
                string Message = ex.Message + "\n\nCannot open "
                                 + fdMockFile.FileName;
                MessageBox.Show(Message, "Open error",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
                return;
            }


        }
        private void handlePictureButtons()
        {
            btnPrevImage.Enabled = false;
            btnNextImage.Enabled = false;
            if (CurrentPlant.PlantPictures.Length > 0)
            {
                btnPrevImage.Enabled = true;
                btnNextImage.Enabled = true;
                if (plantPictureCount == 0)
                {
                    btnPrevImage.Enabled = false;
                }
                if (plantPictureCount == (CurrentPlant.PlantPictures.Length - 1))
                {
                    btnNextImage.Enabled = false;
                }
                //load the picture
                try
                {
                    Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                    plantPic.Image = LoadPicture(CurrentPlant.PlantPictures[plantPictureCount].PlantPictureURL).GetThumbnailImage(100, 93, myCallback, IntPtr.Zero);
                }
                catch
                {
                    //do nothing
                }
            }

        }
        public bool ThumbnailCallback()
        {
            return false;
        }
        private void btnImagePreviewPic_Click(object sender, EventArgs e)
        {
            l_cam.OpenConnection();
            setPicWindow(true);
        }
        private void setPicWindow(bool bPreview)
        {
            btnImagePreviewPic.Visible = !bPreview;
            btnImageCancelPic.Visible = bPreview;
            btnImageSavePic.Visible = bPreview;
        }
        private void btnImageSavePic_Click(object sender, EventArgs e)
        {
            Image returnImage = l_cam.SaveGetImage();
            MemoryStream sImageStream = new MemoryStream();

            returnImage.Save(sImageStream, System.Drawing.Imaging.ImageFormat.Gif);
            byte[] mybytearray = sImageStream.ToArray();
            //save image off to web service
            ws_insertPlant(3, CurrentPlant.PlantID.ToString(), Guid.NewGuid(), mybytearray, "gif");

            //reload camera settings
            reloadCameraSettings();
        }
        private void reloadCameraSettings()
        {
            //reload plant
            CurrentPlant = WsPlant.getPlantInfo(CurrentPlantID);
            //stop preview
            setPicWindow(false);
            //stop camera
            l_cam.Dispose();
            //reload images
            handlePictureButtons();
        }
        private void btnImageCancelPic_Click(object sender, EventArgs e)
        {
            l_cam.Dispose();
            setPicWindow(false);
        }
        private void btnNextImage_Click_1(object sender, EventArgs e)
        {
            //next image
            plantPictureCount++;
            handlePictureButtons();
        }
        private void btnPrevImage_Click_1(object sender, EventArgs e)
        {
            //go to the previous pic
            plantPictureCount--;
            handlePictureButtons();
        }
        private Bitmap LoadPicture(string url)
        {
            HttpWebRequest wreq;
            HttpWebResponse wresp;
            Stream mystream;
            Bitmap bmp;

            bmp = null;
            mystream = null;
            wresp = null;
            try
            {
                wreq = (HttpWebRequest)WebRequest.Create(url);
                wreq.AllowWriteStreamBuffering = true;

                wresp = (HttpWebResponse)wreq.GetResponse();

                if ((mystream = wresp.GetResponseStream()) != null)
                    bmp = new Bitmap(mystream);
            }
            finally
            {
                if (mystream != null)
                    mystream.Close();

                if (wresp != null)
                    wresp.Close();
            }

            return (bmp);
        }

        #endregion

        private void tabEdit_Click(object sender, EventArgs e)
        {

        }
        private void btnComment_Click(object sender, EventArgs e)
        {
            //btnComment.Enabled = false;
            //this.enableNewScreen();
            frmComment myForm = new frmComment();
            if (myForm.ShowDialog() == DialogResult.OK)
            {
                //MessageBox.Show("comment with " + myForm.txtPlantComment.Text);
                WsPlant.insertPlantComment(
                    CurrentPlantID
                    , myForm.txtPlantComment.Text
                    , UserID);
                CurrentPlant = WsPlant.getPlantInfo(CurrentPlantID);
                //reload the plant info
                displayPlantInfo();
            }
        }

        private void btnTrim_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.Trim;
            CurrentOperation = Operation.changeState;
            lblCurrentMode.Text = "To trim";
        }

        private void btnCure_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.Curing;
            CurrentOperation = Operation.changeState;
            lblCurrentMode.Text = "To cure";
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.WeighComplete;
            CurrentOperation = Operation.changeState;
            lblCurrentMode.Text = "To store";
            tbMonitor.SelectedTab = tabWeigh;
        }

        private void btnKill_Click(object sender, EventArgs e)
        {
            CurrentState = PlantState.DeadOrRemoved;
            CurrentOperation = Operation.Kill;
            lblCurrentMode.Text = "Killing";
            //set kill tab default
            tbMonitor.SelectedTab = tabKill;
        }

        private void btnAddEditUpdate_Click(object sender, EventArgs e)
        {
            if (txtAddEditTagID.Text.Trim() == "")
            {
                MessageBox.Show("Must provide Tag ID");
                txtAddEditTagID.Focus();
                return;
            }
            //save the plant
            if (!savePlant()) MessageBox.Show("Error in adding plant");
            buildAddScreen();
            disableNewScreen();
        }

        private void btnActionToFlower_Click(object sender, EventArgs e)
        {
            WsPlant.ChangePlantState
                (
                CurrentPlant.PlantID
                , 2
                );
            WsPlant.setFlowerDate(
                CurrentPlant.PlantID
                );
            btnActionToFlower.Visible = false;
        }

        private void btnAddEditCancelReservation_Click(object sender, EventArgs e)
        {
            //cancel the new reservation
            buildAddScreen();
            disableNewScreen();
        }

        private void btnKillTerminate_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("Are you sure??","Confirm",MessageBoxButtons.YesNo)==DialogResult.Yes)
            {
                WsPlant.ChangePlantState
                (
                CurrentPlant.PlantID
                , (int)PlantState.DeadOrRemoved
                );
            }

        }


    }
    public class KeyValuePair
    {

        public int Key;
        public string Value;

        public KeyValuePair(int NewValue, string NewDescription)
        {
            Key = NewValue;
            Value = NewDescription;
        }

        public override string ToString()
        {
            return Value;
        }
    }
}
